package controllers

import (
	"xdkaika/libs/jwt"
	"xdkaika/libs/wx"
	"xdkaika/models"
)

// Operations about Users
type WechatController struct {
	BaseController
}

// @Title Login
// @Description Logs user into the system
// @Param	username		query 	string	true		"The username for login"
// @Param	password		query 	string	true		"The password for login"
// @Success 200 {string} login success
// @Failure 500 add user failure
// @router /login [get]
func (c *WechatController) Login() {
	//获取code
	var code string
	if v := c.GetString("code"); v != "" {
		code = v
	}
	//获取小程序实例
	mp := wx.GetMiniProgram()
	auth := mp.GetAuth()
	//获取openid
	resp, err := auth.Code2Session(code)

	if err != nil {
		c.ServerError(100001, "小程序登录失败", resp)
		return
	}
	//验证用户
	var userprofile *models.UserProfile
	user, _ := models.GetUserByOpenId(resp.OpenID)
	if user == nil {
		user = &models.User{}
		user.OpenId = resp.OpenID
		id, err := models.AddUser(user)
		if err != nil {
			c.ServerError(100002, "新增用户失败", err)
			return
		}
		user, err := models.GetUserById(int(id))
		if err != nil {
			c.ServerError(100003, "新增用户失败", err)
			return
		}
		userprofile = models.GetUserProfile(user)
	} else {
		userprofile = models.GetUserProfile(user)
	}
	token, err := jwt.GenerateToken(user)
	if err != nil {
		c.ServerError(100004, "令牌生产错误", err)
		return
	}
	res := make(map[string]interface{})
	res["token"] = token
	res["user"] = userprofile
	c.SuccessResult(res)
}

// @Title logout
// @Description Logs out current logged in user session
// @Success 200 {string} logout success
// @router /logout [get]
func (c *WechatController) Logout() {

	if c.UserProfile.OpenId != "" {
		res, err := jwt.DeleteToken(&c.UserProfile)
		if res {
			c.SuccessResult()
		} else {
			c.ServerError(100005, "令牌错误", err)
		}
	}
	c.SuccessResult()
}
